<?php
    error_reporting(0);
    define('__ROOT__', dirname(dirname(__FILE__)));
    require_once(__ROOT__.'\config\config.php'); 
    require_once (__ROOT__.'\model\db.php');
    require_once (__ROOT__.'\model\bill.php');
    require_once (__ROOT__.'\model\products.php');
    require_once (__ROOT__.'\model\bill_detail.php');
    $bill = new Bill();
    $bill_detail = new Bill_detail();
    $product = new Products();
    if(empty($_SESSION))
        session_start ();
    if(isset($_SESSION['email']))                  
    {
        if(isset($_GET['cost']))
        {
            $flag = 0;
            foreach($_SESSION['cartitem'] as $item) :
                $products = $product->selectname($item['name']);
                if($products[0]['quantity'] < $item['quantity'])
                    $flag = 1;
            endforeach;
            if($flag == 0)
            {
                $bills = $bill->insert($_SESSION['name'], $_GET['cost']);
                $billss = $bill->selectMAXID();
                foreach($_SESSION['cartitem'] as $item) :
                    $products = $product->selectname($item['name']);
                    $quantity = $products[0]['quantity'] - $item['quantity'];
                    $products = $product->updatename($item['name'],$quantity);
                    $cost = $item['quantity']*$item['price'];
                    $bill_details = $bill_detail->insert($item['name'], $item['quantity'], $cost, $billss[0]['ID']);
                endforeach;
                unset($_SESSION["cartitem"]);
                echo("<script>location.href = '".HOST."view/view_checkout.php';</script>");
            }
            else
            {
                echo("<script>location.href = '".HOST."view/view_checkouterror.php';</script>");
            }
           
        }
    }           
    else{
        echo("<script>location.href = '".HOST."/view/view_signup-login.php';</script>");
    }
?>